# -*- coding: utf-8 -*-
import pymysql
from datetime import datetime
import logging

from resource.MysqlConf import mysql_host
from resource.MysqlConf import mysql_user
from resource.MysqlConf import mysql_password
from resource.MysqlConf import mysql_database

logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s', datefmt='[%Y%m%d-%H:%M:%S]')


# 插入sql
def insert_sql(sql_format, sql_value):
    db = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_database)
    db_curs = db.cursor()
    # insert data insert_sql = """INSERT INTO nginx_log_statistcs(time, type, count, hostname, gmt_created) VALUES (
    # %s,%s,%s,%s,%s);"""
    logging.info(sql_format)
    try:
        db_curs.executemany(sql_format, sql_value)
        db.commit()
        logging.info("数据写入成功。")
    except Exception as e:
        logging.error(e)
        db.rollback()
        logging.error("数据写入失败。")
    db.close()


#  查询sql
def search_sql(sql_format):
    db = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_database)
    db_curs = db.cursor()
    # insert data
    # insert_sql = """INSERT INTO nginx_log_statistcs(time, type, count, hostname, gmt_created)
    # VALUES (%s,%s,%s,%s,%s);"""
    logging.info(sql_format)
    try:
        db_curs.execute(sql_format)
        rows = db_curs.fetchall()
        # db.commit()
        logging.info("数据查询成功。")
    except Exception as e:
        logging.error(e)
        db.rollback()
        logging.error("数据写入失败。")
    db.close()
    return rows


today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def insert_movie_record(movie_list):
    sql_format = '''REPLACE INTO movie(id, name,  poster_url, movie_desc, download_info, 
    data_date, recommend, created_time) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);'''
    insert_sql(sql_format, movie_list)


def insert_recommend_movie_record(movie_list):
    sql_format = '''
    REPLACE INTO recommend_movie(id, name,  poster_url, data_date, created_time) 
    VALUES (%s,%s,%s,%s,%s);'''
    insert_sql(sql_format, movie_list)


def get_movie_by_id(movie_id):
    sql_format = f''' 
    select id, name, poster_url, movie_desc, download_info, data_date, recommend 
    from movie   
    where id = {movie_id}'''
    result = search_sql(sql_format)
    return result


def get_new_movie_list():
    sql_format = f''' 
    select id, name, data_date, recommend 
    from movie  order by id desc 
    limit 30 '''
    result = search_sql(sql_format)
    return result


def get_recommend_movie_list():
    sql_format = f''' 
    select id, name, poster_url 
    from recommend_movie order by id desc    
    limit 5 '''
    result = search_sql(sql_format)
    return result
